## 控制器模板

import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.linln.component.actionLog.action.SaveAction;
import com.linln.component.actionLog.action.StatusAction;
import com.linln.component.actionLog.annotation.ActionLog;
import com.linln.component.actionLog.annotation.EntityParam;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.linln.component.excel.config.ExportCellWriteHandler;
import com.linln.common.utils.ReflectUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author taofucheng
 * @date 2019/4/4
 */
@Controller
@RequestMapping("#{requestMapping}")
@Slf4j
public class #{entity}Controller {

    @Autowired
    private #{entity}Service #{name}Service;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("#{permissions}:index")
    public String index(Model model, #{entity} #{name}){

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 获取数据列表
        Example<#{entity}> example = Example.of(#{name}, matcher);
        Page<#{entity}> list = #{name}Service.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "#{requestMapping}/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("#{permissions}:add")
    public String toAdd(){
        return "#{requestMapping}/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("#{permissions}:edit")
    public String toEdit(@PathVariable("id") #{entity} #{name}, Model model){
        model.addAttribute("#{name}", #{name});
        return "#{requestMapping}/add";
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"#{permissions}:add", "#{permissions}:edit"})
    @ActionLog(name = "#{title}", action = SaveAction.class)
    @ResponseBody
    public ResultVo save(@Validated #{entity}Valid valid, @EntityParam #{entity} #{name}){
        // 复制保留无需修改的数据
        if(#{name}.getId() != null){
            #{entity} be#{entity} = #{name}Service.getById(#{name}.getId());
            EntityBeanUtil.copyProperties(be#{entity}, #{name});
        }

        // 保存数据
        #{name}Service.save(#{name});
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("#{permissions}:detail")
    public String toDetail(@PathVariable("id") #{entity} #{name}, Model model){
        model.addAttribute("#{name}",#{name});
        return "#{requestMapping}/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("#{permissions}:status")
    @ActionLog(name = "#{title}状态", action = StatusAction.class)
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids){
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (#{name}Service.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
    /**
     * 导出列表数据
     */
    @GetMapping("/export")
    @RequiresPermissions("#{permissions}:export")
    public void exportExcel(#{entity} #{name}, HttpServletResponse response) {
        int perPage = 100;
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String("公司信息数据".getBytes(StandardCharsets.UTF_8), "ISO-8859-1") + ".xlsx");
            response.setContentType("application/octet-stream");
            ExcelWriter excelWriter = EasyExcel.write(os).excelType(ExcelTypeEnum.XLSX).build();
            try {
                List<List<String>> head = new ArrayList<>();
                String[] fields = new String[]{#{showFields}};
                String[] heads = new String[]{#{showHeaders}};
                for (String title : heads) {
                    head.add(Arrays.asList(title));
                }
                CellWriteHandler cellWriteHandler = new ExportCellWriteHandler();
                WriteSheet writeSheet = EasyExcel.writerSheet("列表数据").head(head).registerWriteHandler(cellWriteHandler).build();
                int page = 1;
                while (true) {
                    ExampleMatcher matcher = ExampleMatcher.matching();
                    Example<#{entity}> example = Example.of(#{name}, matcher);
                    Page<#{entity}> list = #{name}Service.getPageList(example, page, perPage);
                    if (list == null || list.isEmpty()) {
                        break;
                    }
                    List<List<Object>> lines = new ArrayList<>();
                    for (#{entity} one : list) {
                        List<Object> ele = new ArrayList<>();
                        for (String field : fields) {
                            Object val = BeanUtils.getProperty(one, field);
                            if(val instanceof Date){
                                val = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(val);
                            } else if (val instanceof User) {
                                val = ((User) val).getNickname();
                            }
                            ele.add(val);
                        }
                        lines.add(ele);
                    }
                    // 写入到Excel中
                    excelWriter.write(lines, writeSheet);
                    ++page;
                }
            }finally {
                excelWriter.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            try {
                os.close();
            } catch (Exception ignore) {
            }
        }
    }
}
